﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using DataManageSystem.Exceptions;
using DataManageSystem.Models;
using DataManageSystem.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Http;

namespace DataManageSystem.Utils
{
    public static class TokenUtils
    {
        public static User? GetCurrentUser(IHttpContextAccessor httpContextAccessor, UserServices userService, IConfiguration config)
        {
            try
            {
                var request = httpContextAccessor.HttpContext?.Request;
                if (request == null)
                    return null;

                string? token = request.Headers["token"].ToString().Replace("Bearer ", "");
                if (string.IsNullOrEmpty(token))
                {
                    return null;
                }

                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes(config["Jwt:Key"]);
                var validations = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ClockSkew = TimeSpan.Zero,
                };

                var principal = tokenHandler.ValidateToken(token, validations, out var validatedToken);
                string? userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;

                if (!string.IsNullOrEmpty(userId) && int.TryParse(userId, out int parsedUserId))
                {
                    return userService.getUserById(parsedUserId); // 查询数据库
                }
            }
            catch (Exception ex)
            {
                throw new ServiceException($"Token 验证失败, {ex.Message}");
            }

            return null;
        }
    }


}
